import 'dart:math';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/default_style.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:leader_doctor_flutter/common/utils/date_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/general_dialog_content_widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:leader_doctor_flutter/ui/task/meeting/model/work_station_time_select_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../../common/data/app.dart';
import '../../../../common/http/api.dart';
import '../../../../common/http/http_client.dart';
import '../../../../common/widget/over_scroll_behavior.dart';
import '../../../../common/widget/pop_route.dart';
import '../model/task_data.dart';

/// @Author lixiaobin
/// @Date 2024/3/11
/// @Description 医学

class WorkstationPage extends StatefulWidget {
  const WorkstationPage({super.key});

  @override
  State<WorkstationPage> createState() => _WorkstationPageState();
}

class _WorkstationPageState extends State<WorkstationPage> {
  final List<WorkStationCommonTimeItemModel> topFilterItems = [
    WorkStationCommonTimeItemModel(title: "本月", titleType: "", isSelected: true, id: "0"),
    WorkStationCommonTimeItemModel(title: "上月", titleType: "", isSelected: false, id: "1"),
    WorkStationCommonTimeItemModel(title: "近3个月", titleType: "", isSelected: false, id: "2"),
    WorkStationCommonTimeItemModel(title: "近6个月", titleType: "", isSelected: false, id: "3"),
    WorkStationCommonTimeItemModel(title: "近12个月", titleType: "", isSelected: false, id: "4"),
  ];
  var defArr = [
    TaskTotalModel()
      ..value = 0
      ..name = '邀请我的任务'
      ..desc = '所选时间范围内，邀请我的任务数量',
    TaskTotalModel()
      ..value = 0
      ..name = '我领取的任务'
      ..desc = '所选时间范围内，我领取的任务数量',
    TaskTotalModel()
      ..value = 0
      ..name = '我完成的任务'
      ..desc = '所选时间范围内，我完成的任务数量',
  ];
  String startTimeStr = MyDateUtils.getCurrentDate("yyyy-MM");
  String endTimeStr = MyDateUtils.getCurrentDate("yyyy-MM");

  // 点击弹框时选择的, -1时为自定义时间
  int selectBtnIndex = 0;

  // 选择完之后点击确认按钮时的, -1时为自定义时间
  int confirmSelectBtnIndex = 0;

  // 主页顶部时间显示文案 默认本月，选择过时间后展示的是 startTimeStr - endTimeStr
  String timeStr = "本月";
  TaskDataCountModel? _taskDataCountModel;
  var keys = [GlobalKey(), GlobalKey(), GlobalKey()];
  final _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    _medicalTaskDataCount();
    _refreshController.refreshCompleted();
  }

  BarTouchData get barTouchData => BarTouchData(
        enabled: false,
        touchTooltipData: BarTouchTooltipData(
          tooltipBgColor: ColorRes.transparent,
          tooltipPadding: EdgeInsets.zero,
          tooltipMargin: 0.w,
          getTooltipItem: (
            BarChartGroupData group,
            int groupIndex,
            BarChartRodData rod,
            int rodIndex,
          ) {
            var title = rod.toY;
            if (title == 0.01) {
              title = 0;
            }
            return BarTooltipItem(
              title.toInt().toString(),
              const TextStyle(color: ColorRes.color333333),
            );
          },
        ),
      );

  @override
  void initState() {
    _medicalTaskDataCount();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var totalList = _taskDataCountModel?.totalList ?? defArr;
    var arr = totalList.mapIndexed((index, e) => _buildTaskTotal(e.value, e.name, e.desc, keys[index])).toList();
    arr.forEachIndexed((index, element) {
      if (index < totalList.length - 1) {
        arr.insert((index + 1) * 2 - 1, _buildLine());
      }
    });
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
          toolbarHeight: 0,
          shadowColor: Colors.transparent,
          backgroundColor: Colors.transparent,
          systemOverlayStyle: const SystemUiOverlayStyle(
            systemNavigationBarColor: Color(0xFF000000),
            systemNavigationBarIconBrightness: Brightness.light,
            statusBarIconBrightness: Brightness.light,
            statusBarBrightness: Brightness.dark,
          )),
      body: Column(children: [
        Stack(children: [
          SizedBox(
            height: 210.w,
            child: ImageLoader.loadAsset('icon_ws_bg.webp', double.infinity, fit: BoxFit.fill),
          ),
          SizedBox(height: 50.w),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildPageTitleBar(context),
              SizedBox(height: 10.w),
              GestureDetector(
                onTap: () {
                  // 遍历列表，根据主弹框确认后的常用时间index，设置按钮isSelected 为 true进行内容回显,重置其它按钮的 isSelected 为 false
                  topFilterItems.asMap().forEach((index, model) {
                    if (index == confirmSelectBtnIndex) {
                      model.isSelected = true;
                      selectBtnIndex = confirmSelectBtnIndex;
                      _handleFilterItemTap(model.id, index, context);
                    } else {
                      model.isSelected = false;
                    }
                  });
                  _timeSelectorView();
                },
                child: Row(
                  children: [
                    SizedBox(width: 16.w),
                    Text(
                      timeStr,
                      style: TextStyle(fontSize: 15.sp, color: ColorRes.white),
                    ),
                    SizedBox(width: 7.w),
                    ImageLoader.loadAsset('icon_arrows.webp', 20.w),
                  ],
                ),
              ),
              SizedBox(height: 20.w),
              Row(mainAxisAlignment: MainAxisAlignment.center, children: arr),
            ],
          )
        ]),
        Expanded(child: _buildBarLayout())
      ]),
    );
  }

  Widget _buildBarLayout() {
    return _taskDataCountModel == null
        ? CommWidget.buildEmptyView()
        : Container(
            padding: EdgeInsets.only(left: 16.w, right: 16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 23.w),
                Text('任务类型统计',
                    style: TextStyle(fontSize: 17.sp, color: ColorRes.color333333, fontWeight: FontWeight.w600)),
                SizedBox(height: 13.w),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: (_taskDataCountModel?.data?.itemDesc ?? []).map((e) => _buildTaskColorInfoView(e)).toList(),
                ),
                SizedBox(height: 10.w),
                Expanded(
                    child: SingleChildScrollView(
                        physics: const BouncingScrollPhysics(),
                        child: Column(
                          children: [
                            SizedBox(height: 10.w),
                            GridView.count(
                              padding: EdgeInsets.zero,
                              shrinkWrap: true,
                              childAspectRatio: 0.9,
                              crossAxisCount: 2,
                              mainAxisSpacing: 13.w,
                              crossAxisSpacing: 13.w,
                              physics: const NeverScrollableScrollPhysics(),
                              children:
                                  (_taskDataCountModel?.data?.itemData ?? []).map((e) => _buildBarItem(e)).toList(),
                            ),
                            SizedBox(height: 40.w),
                          ],
                        ))),
              ],
            ),
          );
  }

  Widget _buildPageTitleBar(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        height: 50.w,
        width: double.infinity,
        child: Stack(
          children: [
            IconButton(
              icon: const Icon(Icons.arrow_back, color: ColorRes.white),
              onPressed: () async {
                FocusScope.of(context).unfocus();
                var canPop = context.canPop();
                if (canPop) {
                  context.pop();
                } else {
                  SystemNavigator.pop();
                }
              },
            ),
            Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.center,
                child: Text(
                  ModalRoute.of(context)?.settings.name ?? '',
                  style: TextStyle(color: ColorRes.white, fontSize: 18.sp),
                ))
          ],
        ));
  }

  /// 柱壮图分类
  Widget _buildBarItem(TaskItemDataModel? item) {
    var maxY = (item?.items?.map((e) => e.total ?? 0).toList() ?? []).maxOrNull ?? 0;
    return Container(
      decoration: BoxDecoration(color: ColorRes.colorf5f7fb, borderRadius: BorderRadius.circular(4.w)),
      padding: EdgeInsets.only(left: 10.w, right: 10.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 10.w),
          Text(
            item?.taskName ?? '',
            style: TextStyle(fontSize: 14.sp, color: ColorRes.color333333),
          ),
          SizedBox(height: 30.w),
          Expanded(
              child: BarChart(
            BarChartData(
              barTouchData: barTouchData,
              barGroups: _buildBarGroups(item?.items),
              titlesData: const FlTitlesData(show: false),
              borderData: FlBorderData(show: false),
              gridData: const FlGridData(show: false),
              alignment: BarChartAlignment.spaceAround,
              maxY: maxY.toDouble(),
            ),
          )),
          SizedBox(height: 13.w)
        ],
      ),
    );
  }

  /// 任务类型柱状图说明
  Widget _buildTaskColorInfoView(TaskItemDataModel? item) {
    return Row(
      children: [
        Container(
          width: 14.w,
          height: 5.w,
          decoration: BoxDecoration(
              color: Color(StringUtils.getColor(item?.colourValue)), borderRadius: BorderRadius.circular(2.5.w)),
        ),
        SizedBox(width: 5.w),
        Text(item?.name ?? '', style: TextStyle(fontSize: 12.sp, color: ColorRes.color666666)),
        SizedBox(width: 12.w),
      ],
    );
  }

  Widget _buildLine() {
    return Container(
      height: 22.w,
      width: 0.5.w,
      color: ColorRes.white,
    );
  }

  /// 任务总计
  Widget _buildTaskTotal(int? num, String? name, String? desc, GlobalKey key) {
    return SizedBox(
        width: (ScreenUtil().screenWidth / 3) - 2,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              StringUtils.thousandthFormat(num ?? 0),
              style: TextStyle(fontSize: 17.sp, color: ColorRes.white, fontWeight: FontWeight.w600),
            ),
            SizedBox(height: 5.w),
            GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (desc == null) return;
                  Navigator.push(
                      context,
                      PopRoute(
                          child: Popup(
                        globalKey: key,
                        margin: EdgeInsets.only(top: 4.w),
                        children: [
                          WidgetModel(ImageLoader.loadAsset('icon_pop_up_arrows.webp', 0, size: Size(14.w, 8.w)),
                              Size(14.w, 8.w)),
                          WidgetModel(_buildPopupWindow(desc), Size(150.w, 0.w)),
                        ],
                      )));
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      name ?? '',
                      maxLines: 3,
                      style: TextStyle(fontSize: 12.sp, color: ColorRes.white),
                    ),
                    SizedBox(width: 2.w),
                    ImageLoader.loadAsset('icon_alert_task.png', 12.w, key: key),
                  ],
                )),
          ],
        ));
  }

  /// 数据填充
  List<BarChartGroupData> _buildBarGroups(List<TaskItemDataModel>? arr) {
    return arr?.mapIndexed((i, e) {
          var total = (e.total ?? 0).toDouble();
          return BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: (total == 0) ? 0.01 : total,
                color: Color(StringUtils.getColor(e.colourValue)),
                width: 18,
                borderRadius: BorderRadius.circular(2.w),
              ),
            ],
            showingTooltipIndicators: [0],
          );
        }).toList() ??
        [];
  }

  /// PopupWindow 提示弹窗
  Widget _buildPopupWindow(String tipStr) {
    return Container(
      alignment: Alignment.center,
      width: 152.w,
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
          color: ColorRes.color3d3d3d,
          borderRadius: BorderRadius.circular(8.w),
          border: Border.all(color: ColorRes.color3d3d3d, width: 0)),
      child: Text(tipStr, maxLines: 3, style: TextStyle(color: ColorRes.white, fontSize: 14.sp)),
    );
  }

  /// 工作站-医学数据统计接口
  _medicalTaskDataCount() async {
    String startYearStr = _formatDateString(startTimeStr, "yyyy");
    String startMonthStr = _formatDateString(startTimeStr, "MM");
    String startTime = MyDateUtils.getFirstDayOfMonthString(int.parse(startYearStr), int.parse(startMonthStr));

    String endYearStr = _formatDateString(endTimeStr, "yyyy");
    String endMonthStr = _formatDateString(endTimeStr, "MM");
    String endTime = MyDateUtils.getLastDayOfMonthString(int.parse(endYearStr), int.parse(endMonthStr));

    print("开始 = ${startTime}");
    print("结束 = ${endTime}");

    var user = App.instance.userInfo;
    var response = await HttpClient.post(HttpRequest(Api.medicalTaskDataCount, urlParams: {
      'startTime': startTime,
      'endTime': endTime,
      'version': '1',
      'medicalId': user?.id ?? '',
    }));
    var serviceResult = ServiceResult<TaskDataCountModel>(response, (map) => TaskDataCountModel.fromJson(map));
    if (serviceResult.success) {
      _taskDataCountModel = serviceResult.responseBody;
      setState(() {});
    }
  }

  // pragma mark -- 弹框部分
  // 时间筛选
  _timeSelectorView() {
    print("时间筛选");
    return Container(
      width: double.infinity,
      child: BottomGeneralDialog.showBottomGeneralDialog(
        context,
        title: "选择时间范围",
        desc: "",
        cancelTextColor: ColorRes.colorMain,
        cancelButtonColor: ColorRes.colorEDEDFD,
        cancelBoxDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.w),
          border: Border.all(
            color: ColorRes.colorMain,
            width: 1.w,
          ),
          color: ColorRes.colorEDEDFD,
        ),
        confirmButtonColor: ColorRes.colorMain,
        confirmBoxDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.w),
          border: Border.all(
            color: ColorRes.colorMain,
            width: 1.w,
          ),
          color: ColorRes.colorMain,
        ),
        descContainer: (c) => Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _titleView("常用时间"),
              SizedBox(
                height: 12.w,
              ),
              Container(
                width: double.infinity,
                color: Colors.white,
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    return Wrap(
                      spacing: 15.w,
                      runSpacing: 10.w,
                      //横轴对齐方式
                      alignment: WrapAlignment.start,
                      //纵轴对齐方式
                      runAlignment: WrapAlignment.end,
                      children: buildFilterWidgets(topFilterItems, constraints.maxWidth, c),
                    );
                  },
                ),
              ),
              SizedBox(
                height: 18.w,
              ),
              _titleView("自定义时间"),
              SizedBox(
                height: 12.w,
              ),
              Container(
                height: 30.w,
                width: double.infinity,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: _timeButton("${startTimeStr}", "icon_time.webp", () {
                        String displayedStarTime = startTimeStr;
                        print("点击了自定义时间 - 开始时间：${displayedStarTime}");
                        String startYearStr = _formatDateString(displayedStarTime, "yyyy");
                        String startMonthStr = _formatDateString(displayedStarTime, "MM");
                        print("startTime = ${startYearStr}, ${startMonthStr}");
                        Pickers.showDatePicker(context,
                            mode: DateMode.YM,
                            selectDate: PDuration(
                              year: int.parse(startYearStr),
                              month: int.parse(startMonthStr),
                            ),
                            minDate: PDuration(year: 2000, month: 1, day: 1),
                            maxDate: PDuration(
                              year: _getCurrentDate("yyyy"),
                              month: _getCurrentDate("MM"),
                              day: _getCurrentDate("dd"),
                            ),
                            pickerStyle:
                                RaisedPickerStyle(haveRadius: true, title: "时间选择", color: ColorRes.colorMain),
                            onConfirm: (p) {
                          String selectTimeStr = "${p.year}-${p.month}";
                          startTimeStr = MyDateUtils.addLeadingZero(selectTimeStr);
                          selectBtnIndex = -1;
                          if (validateDates(startTimeStr, endTimeStr)) {}
                          _refreshBtnStatus(c);
                        });
                      }),
                    ),
                    SizedBox(width: 20.w),
                    Container(
                      width: 15.w,
                      height: 1.w,
                      color: ColorRes.color333333,
                    ),
                    SizedBox(width: 20.w),
                    Expanded(
                      child: _timeButton("${endTimeStr}", "icon_time.webp", () {
                        String displayedEndTime = endTimeStr;

                        print("点击了自定义时间 - 结束时间：${displayedEndTime}");
                        String endYearStr = _formatDateString(displayedEndTime, "yyyy");
                        String endMonthStr = _formatDateString(displayedEndTime, "MM");
                        print("endTime = ${endYearStr}, ${endMonthStr}");
                        Pickers.showDatePicker(context,
                            mode: DateMode.YM,
                            selectDate: PDuration(
                              year: int.parse(endYearStr),
                              month: int.parse(endMonthStr),
                            ),
                            minDate: PDuration(year: 2000, month: 1, day: 1),
                            maxDate: PDuration(
                              year: _getCurrentDate("yyyy"),
                              month: _getCurrentDate("MM"),
                              day: _getCurrentDate("dd"),
                            ),
                            pickerStyle:
                                RaisedPickerStyle(haveRadius: true, title: "时间选择", color: ColorRes.colorMain),
                            onConfirm: (p) {
                          String selectTimeStr = "${p.year}-${p.month}";
                          endTimeStr = MyDateUtils.addLeadingZero(selectTimeStr);
                          print('结束时间：$selectTimeStr');
                          selectBtnIndex = -1;
                          if (validateDates(startTimeStr, endTimeStr)) {}
                          _refreshBtnStatus(c);
                        });
                      }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        buttonFontSize: 14.sp,
        onConfirm: () {
          if (validateDates(startTimeStr, endTimeStr)) {
            confirmSelectBtnIndex = selectBtnIndex;
            // confirmStartTimeStr = startTimeStr;
            // confirmEndTimeStr = endTimeStr;
            timeStr = "${startTimeStr} ~ ${endTimeStr}";
            context.pop();
            setState(() {
              _medicalTaskDataCount();
            });
          }
        },
        onCancel: () {
          print("取消");
        },
      ),
    );
  }

  /// 遍历列表，重置所有按钮的 isSelected 为 false
  _refreshBtnStatus(BuildContext context) {
    topFilterItems.forEach((item) {
      item.isSelected = false;
    });
    (context as Element).markNeedsBuild();
  }

  /// 时间弹框选择时间的按钮 GestureDetector 点击事件
  List<Widget> buildFilterWidgets(
      List<WorkStationCommonTimeItemModel> items, double constraints, BuildContext context) {
    return items
        .mapIndexed(
          (index, e) => GestureDetector(
            onTap: () {
              _handleFilterItemTap(e.id, index, context);
            },
            child: Container(
              height: 30.w,
              width: (constraints - 30.w) / 3,
              //(constraints.maxWidth - 30.w) / 3,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: e.isSelected == true ? ColorRes.colorMain : ColorRes.colorF5F7FB,
                  borderRadius: BorderRadius.circular(20.w)),
              child: Text(e.title,
                  style: TextStyle(color: e.isSelected == true ? Colors.white : ColorRes.color333333, fontSize: 14.sp)),
            ),
          ),
        )
        .toList();
  }

  // 点击时的时间组装逻辑
  _handleFilterItemTap(String id, int index, BuildContext context) {
    if (id == "0") {
      // 当前月e.isSelected = true;
      _displayMonthRange("当前月份", MyDateUtils.getCurrentMonthStartDate(DateTime.now()), DateTime.now());
    } else if (id == "1") {
      // 上个月
      _displayMonthRange("上个月", MyDateUtils.getPreviousMonthFirstDate(DateTime.now()),
          MyDateUtils.getPreviousMonthLastDate(DateTime.now()));
    } else if (id == "2") {
      // 近3个月
      _displayMonthRange("近3个月", MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 3),
          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
    } else if (id == "3") {
      // 近6个月
      _displayMonthRange("近6个月", MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 6),
          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
    } else if (id == "4") {
      // 近12个月
      _displayMonthRange("近12个月", MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 12),
          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
    }

    // 遍历列表，重置所有按钮的 isSelected 为 false
    topFilterItems.forEach((item) {
      item.isSelected = false;
    });
    // 设置当前选中项的状态为 true
    topFilterItems[index].isSelected = true;
    selectBtnIndex = index;
    (context as Element).markNeedsBuild();
  }

  // 根据格式返回当前时间对应的年、月、日
  int _getCurrentDate(String format) {
    return int.parse(MyDateUtils.getCurrentDate(format));
  }

  // 根据传入的时间返回对应格式的年、月、日
  String _formatDateString(String timeStr, String format) {
    return MyDateUtils.formatDateString(timeStr, format);
  }

  /// 开始日期和结束日期校验
  bool validateDates(String startYearMonth, String endYearMonth) {
    DateFormat format = DateFormat("yyyy-MM");
    DateTime startDate = format.parse(startYearMonth + "-01");
    DateTime endDate = format.parse(endYearMonth + "-01");

// 如果结束时间早于开始时间，则返回 false
    if (endDate.isBefore(startDate)) {
      Fluttertoast.showToast(msg: "结束日期不能早于开始日期");
      return false;
    }

    // 提取开始时间和结束时间的年份和月份
    int startYear = startDate.year;
    int startMonth = startDate.month;
    int endYear = endDate.year;
    int endMonth = endDate.month;

    // 计算年份差异
    int yearDifference = endYear - startYear;

    // 计算月份差异
    int monthDifference = endMonth - startMonth + 1; // 加1是因为要包含开始月份

    // 如果年份差异大于1，或者年份差异为1且月份差异超过0，则超过12个月
    if (yearDifference > 1 || (yearDifference == 1 && monthDifference > 0)) {
      Fluttertoast.showToast(msg: "起始日期和结束日期的跨度不能超过12个月");
      return false;
    }

    return true;
  }

  /// 常用时间 - 点击分类后获取到对应的开始时间和结束时间
  _displayMonthRange(String title, DateTime startDate, DateTime endDate) {
    startTimeStr = MyDateUtils.getAtWillFormattedDateTime(startDate, "yyyy-MM");
    endTimeStr = MyDateUtils.getAtWillFormattedDateTime(endDate, "yyyy-MM");
  }

  Widget _titleView(String? title) {
    return Container(
      child: Text(
        title ?? "",
        style: TextStyle(fontSize: 15.sp, color: ColorRes.color333333, fontWeight: FontWeight.w600),
      ),
    );
  }

  // 显示已选择的时间、自定义时间 的按钮
  Widget _timeButton(String title, String iconStr, VoidCallback onPressed) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ColorRes.colorF5F7FB,
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            ImageLoader.loadAsset(iconStr, 14.w), // 左侧图标
            SizedBox(width: 8), // 图标和文本之间的间距
            Text(
              title,
              style: TextStyle(fontSize: 14.sp, color: ColorRes.color333333),
            ),
          ],
        ),
      ),
    );
  }
}
